#include "musicplayer.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QTimer>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
#include <QPropertyAnimation>
#include <QEasingCurve>


MusicPlayer::MusicPlayer(PlayListWindow *playlistWindow, QWidget *parent)
    : QWidget(parent),
    player(new QMediaPlayer(this)),
    netManager(new QNetworkAccessManager(this)),
    playlistWindow(playlistWindow),
    currentPlayIndex(-1)
{
    // 初始化数据库DAO
    musicDao = new MySqlMusicCollectedDao("127.0.0.1", "qt_pro", "root", "8");
    if (!musicDao->openConnection()) {
        QMessageBox::critical(this, "数据库错误", musicDao->lastError());
    }
    
    // 初始化UI组件
    initUI();
    
    // 加载已收藏歌曲到播放列表
    loadCollectedSongs();
    
    // 连接播放列表窗口的信号
    connectPlaylistSignals();
    
    // 连接播放器信号
    connectPlayerSignals();
}

MusicPlayer::~MusicPlayer()
{
    delete player;
    delete netManager;
    musicDao->closeConnection();
    delete musicDao;
    // 手动释放动画对象（避免潜在内存泄漏）
    if (scrollAnimation) {
        scrollAnimation->deleteLater();
    }
}

// 初始化UI界面
void MusicPlayer::initUI()
{
    setWindowTitle("简易音乐播放器");
    setMinimumSize(420, 400); // 增大最小高度，避免歌词区域过小
    
    // 创建UI组件
    createWidgets();
    
    // 设置UI布局
    setupLayouts();
    
    // 设置UI样式
    applyStyles();
    
    // 连接UI信号
    connectUISignals();
}

// 创建UI组件
void MusicPlayer::createWidgets()
{
    // 搜索框
    searchEdit = new QLineEdit();
    searchEdit->setPlaceholderText("搜索歌曲或歌手...");
    searchEdit->setClearButtonEnabled(true);
    
    // 歌曲信息标签
    titleLabel = new QLabel("暂无歌曲");
    singerLabel = new QLabel("歌手信息");
    
    // 进度条
    progressSlider = new QSlider(Qt::Horizontal);
    progressSlider->setRange(0, 0);
    
    // 控制按钮
    prevBtn = new QPushButton();
    prevBtn->setIcon(QIcon(":/上一首"));
    
    playBtn = new QPushButton();
    playBtn->setIcon(QIcon(":/播放"));
    
    nextBtn = new QPushButton();
    nextBtn->setIcon(QIcon(":/下一首"));
    
    collectBtn = new QPushButton();
    collectBtn->setIcon(QIcon(":/未收藏"));
    
    // 结果弹窗
    resultPopup = new QWidget(this, Qt::Tool | Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus);
    resultPopup->setStyleSheet("background-color: white; border: 1px solid #CCCCCC;border-radius: 2px;");
    resultPopup->setVisible(false);
    
    // 结果列表
    resultView = new QListView(resultPopup);
    model = new QStandardItemModel(this);
    resultView->setModel(model);
    resultView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    resultView->setFocusPolicy(Qt::NoFocus);
    resultView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    resultView->verticalScrollBar()->setStyleSheet(R"(
QScrollBar:vertical {
        border: none;
        background: #F0F0F0;
        width: 12px;
        margin: 0px;
    }
    
    QScrollBar::handle:vertical {
        background: #C0C0C0;
        border-radius: 6px;
        min-height: 20px;
    }
QScrollBar::handle:vertical:hover {
        background: #A0A0A0;
    }
QScrollBar::add-page:vertical, 
    QScrollBar::sub-page:vertical {
        background: #F0F0F0;
    }
QScrollBar::add-line:vertical, 
    QScrollBar::sub-line:vertical {
        border: none;
        background: none;
        width: 0;
        height: 0;
    }
)");
    
    // 弹窗布局
    QVBoxLayout *popupLayout = new QVBoxLayout(resultPopup);
    popupLayout->setContentsMargins(0, 0, 0, 0);
    popupLayout->addWidget(resultView);
    
    resultView->setMinimumHeight(0);
}

// 设置UI布局
void MusicPlayer::setupLayouts()
{
    // 搜索框布局
    QHBoxLayout *searchLayout = new QHBoxLayout();
    searchLayout->addWidget(searchEdit);
    searchEdit->setMaximumHeight(36);
    
    // 歌曲信息布局
    QVBoxLayout *infoLayout = new QVBoxLayout();
    titleLabel->setMinimumHeight(32);
    singerLabel->setMinimumHeight(20);
    titleLabel->setAlignment(Qt::AlignCenter);
    singerLabel->setAlignment(Qt::AlignCenter);
    infoLayout->addWidget(titleLabel);
    infoLayout->addWidget(singerLabel);
    
    // 进度条布局
    QHBoxLayout *progressLayout = new QHBoxLayout();
    progressLayout->setMargin(1);
    progressSlider->setMaximumHeight(20);
    progressLayout->addWidget(progressSlider);
    
    // 时间标签布局
    QHBoxLayout *timeLayout = new QHBoxLayout();
    timeLayout->setMargin(1);
    currentTimeLabel = new QLabel("00:00", this);
    timeLayout->addWidget(currentTimeLabel);
    timeLayout->addStretch();
    totalTimeLabel = new QLabel("--:--", this);
    timeLayout->addWidget(totalTimeLabel);
    currentTimeLabel->setMaximumHeight(16);
    totalTimeLabel->setMaximumHeight(16);
    
    // 控制按钮布局
    QHBoxLayout *controlLayout = new QHBoxLayout();
    controlLayout->addWidget(prevBtn);
    controlLayout->addWidget(playBtn);
    controlLayout->addWidget(nextBtn);
    controlLayout->addWidget(collectBtn);
    
    // 歌词显示布局
    QHBoxLayout *lyricListLayout = new QHBoxLayout();
    lyricListWidget = new QListWidget();
    lyricListLayout->addWidget(lyricListWidget);
//     lyricListWidget->setStyleSheet(R"(
//         QListWidget {
//             background-color: rgba(255, 255, 255, 200);
//             border-radius: 8px;
//             font-size: 10px;
//             outline: none;
//         }
//         QListWidget::item {
//             padding: 6px 12px;
//             border: none;
//             background: transparent;
//             height: 30px;
//         }
//         QListWidget::item:selected {
//             background: transparent;
//             color: #ff5500;
//             font-weight: bold;
//             font-size: 16px;
//         }
// QScrollBar:vertical {
//     border: none;
//     background: #F0F0F0;
//     width: 15px;
//     margin: 0px 0px 0px 0px;
// }
// QScrollBar::handle:vertical {
//     background: #C0C0C0;
//     min-height: 16px;
// border-radius:8px;
// }
// QScrollBar::add-line:vertical,
// QScrollBar::sub-line:vertical {
//     background: none;
//     height: 0px;
//     subcontrol-position: bottom;
//     subcontrol-origin: margin;
// }
// QScrollBar::add-page:vertical,
// QScrollBar::sub-page:vertical {
//     background: none;
// }
//     )");
    lyricListWidget->setFocusPolicy(Qt::NoFocus);
    
    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(searchLayout);
    mainLayout->addLayout(infoLayout);
    mainLayout->addLayout(lyricListLayout); // 歌词区域优先占据空间
    mainLayout->addLayout(progressLayout);
    mainLayout->addLayout(timeLayout);
    mainLayout->addLayout(controlLayout);
    mainLayout->setContentsMargins(20, 4, 20, 10);
    mainLayout->setSpacing(8); // 增大间距，避免控件拥挤
}

// 应用UI样式
void MusicPlayer::applyStyles()
{
    // 搜索框样式
    searchEdit->setStyleSheet(R"(
        QLineEdit {
            font-family:"宋体";
            padding: 6px 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }
    )");
    
    // 歌曲信息标签样式
    titleLabel->setStyleSheet("font-size: 16px; font-weight: bold;");
    singerLabel->setStyleSheet("color: #666;");
    
    // 按钮通用样式
    QString btnStyle = R"(
        QPushButton {
            padding: 6px 12px;
            border-radius: 15px;
            border: none;
            background-color: #f0f0f0;
            font-size: 14px;
        }
        QPushButton:hover {
            background-color: #e0e0e0;
        }
    )";
    
    prevBtn->setStyleSheet(btnStyle);
    playBtn->setStyleSheet(btnStyle);
    nextBtn->setStyleSheet(btnStyle);
    collectBtn->setStyleSheet(
        btnStyle + "QPushButton { background-color: #4CAF50; color: white; }QPushButton:hover{background-color: #ff5500;}");
    
    // 进度条样式
    progressSlider->setStyleSheet(R"(
QSlider::groove:horizontal {
    border: 1px solid #bbb;
    background: white;
    height: 7px;
    border-radius: 5px;
    padding: 0px;
}
QSlider::sub-page:horizontal {
    background: #66e;
    border: 1px solid #777;
    height: 7px;
    border-radius: 4px;
}
QSlider::add-page:horizontal {
    background: #fff;
    border: 1px solid #777;
    height: 7px;
    border-radius: 4px;
}
QSlider::handle:horizontal {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #eee, stop:1 #ccc);
    border: 1px solid rgba(119, 119, 119, 0.3);
    width: 8px;
    height: 8px;
    margin: -5px 0;
    border-radius: 4px;
}
QSlider::handle:horizontal:hover {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #fff, stop:1 #ddd);
    border: 1px solid #444;
}
QSlider::handle:horizontal:pressed {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #ccc, stop:1 #aaa);
    border: 1px solid #444;
}
    )");
    
    QString QListWidgetStyleSheet = R"(
        QListWidget {
            background-color: rgba(255, 255, 255, 200);
            border-radius: 8px;
            font-size: 10px;
            outline: none;
        }
        QListWidget::item {
            padding: 6px 12px;
            border: none;
            background: transparent;
            height: 30px;
        }
        QListWidget::item:selected {
            background: transparent;
            color: #ff5500;
            font-weight: bold;
            font-size: 16px;
        }
    /* 垂直滚动条样式 */
    QScrollBar:vertical {
        background: #f5f5f5;
        width: 12px;
        border-radius: 6px;
        margin: 0;
    }
    QScrollBar::handle:vertical {
        background: #a0a0a0;
        min-height: 30px;
        border-radius: 6px;
    }
    QScrollBar::handle:vertical:hover {
        background: #808080;
    }
    QScrollBar::add-line:vertical,
    QScrollBar::sub-line:vertical {
        background: none;
        height: 0;
    }

    /* 水平滚动条样式 */
    QScrollBar:horizontal {
        background: #f5f5f5;
        height: 12px;
        border-radius: 6px;
        margin: 0;
    }
    QScrollBar::handle:horizontal {
        background: #a0a0a0;
        min-width: 30px;
        border-radius: 6px;
    }
    QScrollBar::handle:horizontal:hover {
        background: #808080;
    }
    QScrollBar::add-line:horizontal,
    QScrollBar::sub-line:horizontal {
        background: none;
        width: 0;
    }
)";
    lyricListWidget->setStyleSheet(QListWidgetStyleSheet);
    
}

// 连接UI信号
void MusicPlayer::connectUISignals()
{
    connect(searchEdit, &QLineEdit::returnPressed, this, &MusicPlayer::onSearchReturnPressed);
    
    QTimer *searchTimer = new QTimer(this);
    searchTimer->setSingleShot(true);
    searchTimer->setInterval(500);
    
    connect(resultView, &QListView::clicked, this, &MusicPlayer::onResultViewClicked);
    connect(playBtn, &QPushButton::clicked, this, &MusicPlayer::onPlayPauseClicked);
    connect(prevBtn, &QPushButton::clicked, this, &MusicPlayer::onPrevClicked);
    connect(nextBtn, &QPushButton::clicked, this, &MusicPlayer::onNextClicked);
    connect(progressSlider, &QSlider::sliderMoved, this, &MusicPlayer::onProgressChanged);
    connect(collectBtn, &QPushButton::clicked, this, &MusicPlayer::onCollectClicked);
}

// 连接播放列表信号
void MusicPlayer::connectPlaylistSignals()
{
    connect(playlistWindow, &PlayListWindow::itemSelected, 
            this, &MusicPlayer::onPlaylistItemSelected);
    connect(playlistWindow, &PlayListWindow::removeMusic, 
            this, &MusicPlayer::onPlaylistRemoveSong);
}

// 连接播放器信号（初始化定时器和动画）
void MusicPlayer::connectPlayerSignals()
{
    connect(player, &QMediaPlayer::positionChanged, 
            this, &MusicPlayer::onPlayerPositionChanged);
    connect(player, &QMediaPlayer::durationChanged, 
            this, &MusicPlayer::onPlayerDurationChanged);
    connect(netManager, &QNetworkAccessManager::finished, 
            this, &MusicPlayer::onNetworkRequestFinished);
    
    // 初始化歌词定时器（200ms间隔，平衡流畅度和性能）
    lyricTimer = new QTimer(this);
    lyricTimer->setInterval(30);
    connect(lyricTimer, &QTimer::timeout, this, &MusicPlayer::updateLyricDisplay);
    
    // 初始化滚动动画指针
    scrollAnimation = nullptr;
}

void MusicPlayer::updateLyricDisplay()
{
    if (player->state() != QMediaPlayer::PlayingState) {
        return;
    }
    
    qint64 position = player->position();
    
    // 查找当前应该显示的歌词行
    int newIndex = -1;
    for (int i = 0; i < lyricTimes.size(); ++i) {
        if (position >= lyricTimes[i] && 
            (i == lyricTimes.size() - 1 || position < lyricTimes[i + 1])) {
            newIndex = i;
            break;
        }
    }
    
    // 如果找到了新的歌词行
    if (newIndex != -1 && newIndex != currentLyricIndex) {
        currentLyricIndex = newIndex;
        
        // 清除之前的高亮
        for (int i = 0; i < lyricListWidget->count(); ++i) {
            QListWidgetItem *item = lyricListWidget->item(i);
            item->setForeground(Qt::black);
            QFont font = item->font();
            font.setPointSize(10);
            font.setBold(false);
            item->setFont(font);
        }
        
        // 高亮当前行
        if (currentLyricIndex < lyricListWidget->count()) {
            QListWidgetItem *currentItem = lyricListWidget->item(currentLyricIndex);
            currentItem->setForeground(QColor("#ff5500"));
            QFont font = currentItem->font();
            font.setBold(true);
            font.setPointSize(14);
            currentItem->setFont(font);
            
            // 滚动到当前行
            lyricListWidget->scrollToItem(currentItem, QAbstractItemView::PositionAtCenter);
        }
    }
    
    // 处理没有匹配歌词行的情况
    // if (newIndex == -1) {
    //     // 如果之前有高亮行，清除高亮
    //     if (currentLyricIndex != -1 && currentLyricIndex < lyricListWidget->count()) {
    //         QListWidgetItem *prevItem = lyricListWidget->item(currentLyricIndex);
    //         prevItem->setForeground(Qt::black);
    //         QFont font = prevItem->font();
    //         font.setBold(false);
    //         font.setPointSize(14);
    //         prevItem->setFont(font);
    //     }
    //     currentLyricIndex = -1;
    // }
    
}


// 加载已收藏歌曲
void MusicPlayer::loadCollectedSongs()
{
    collectedSongs = musicDao->getAllCollectedMusic();
    playlistWindow->updateList(collectedSongs);
}

// 播放指定歌曲
void MusicPlayer::playSong(const MusicInfo &song)
{
    currentSong = song;
    currentPlayIndex = collectedSongs.indexOf(song);
    
    titleLabel->setText(song.title);
    singerLabel->setText(song.singer);
    collectBtn->setIcon(currentSong.isCollected ? QIcon(":/收藏") : QIcon(":/未收藏"));
    
    player->setMedia(QMediaContent(QUrl(song.url)));
    player->play();
    playBtn->setIcon(QIcon(":/播放"));
    music_state = 1;
    
    // 重置歌词
    lyricListWidget->clear();
    lyricMap.clear();
    lyricTimes.clear();
    lyricTimer->stop();
    
    fetchLyrics(song.id);
}

// 播放/暂停
void MusicPlayer::onPlayPauseClicked()
{
    if (music_state) {
        music_state = 0;
        player->pause();
        playBtn->setIcon(QIcon(":/暂停"));
        lyricTimer->stop();
    } else {
        music_state = 1;
        player->play();
        playBtn->setIcon(QIcon(":/播放"));
        if (!lyricTimes.isEmpty()) {
            lyricTimer->start(30);
        }
    }
}

// 上一曲
void MusicPlayer::onPrevClicked()
{
    if (collectedSongs.isEmpty()) return;
    currentPlayIndex = (currentPlayIndex - 1 + collectedSongs.size()) % collectedSongs.size();
    playSong(collectedSongs[currentPlayIndex]);
    playlistWindow->getListWidget()->setCurrentRow(currentPlayIndex);
}

// 下一曲
void MusicPlayer::onNextClicked()
{
    if (collectedSongs.isEmpty()) return;
    currentPlayIndex = (currentPlayIndex + 1) % collectedSongs.size();
    playSong(collectedSongs[currentPlayIndex]);
    playlistWindow->getListWidget()->setCurrentRow(currentPlayIndex);
}

// 进度条拖动
void MusicPlayer::onProgressChanged(int value)
{
    player->setPosition(value);
}

// 播放位置变化
void MusicPlayer::onPlayerPositionChanged(qint64 pos)
{
    progressSlider->setValue(pos);
    QTime time(0, 0);
    time = time.addMSecs(pos);
    currentTimeLabel->setText(time.toString("m:ss"));
}

// 时长变化
void MusicPlayer::onPlayerDurationChanged(qint64 dur)
{
    progressSlider->setRange(0, dur);
    QTime time(0, 0);
    time = time.addMSecs(dur);
    totalTimeLabel->setText(time.toString("m:ss"));
}

// 收藏/取消收藏
void MusicPlayer::onCollectClicked()
{
    if (currentSong.isCollected) {
        collectBtn->setIcon(QIcon(":/未收藏"));
        currentSong.isCollected = false;
        musicDao->removeFromCollection(currentSong.id);
        collectedSongs.removeOne(currentSong);
    } else {
        collectBtn->setIcon(QIcon(":/收藏"));
        currentSong.isCollected = true;
        musicDao->addToCollection(currentSong);
        collectedSongs.append(currentSong);
    }
    playlistWindow->updateList(collectedSongs);
}

// 搜索回车
void MusicPlayer::onSearchReturnPressed()
{
    model->clear();
    QString text = searchEdit->text();
    if (text.isEmpty()) {
        resultPopup->hide();
        return;
    }
    
    QString url = QString("http://music.163.com/api/search/get/web?csrf_token=&s=%1&type=1&offset=0&total=true&limit=10")
                      .arg(text);
    netManager->get(QNetworkRequest(url));
}

// 播放列表项选择
void MusicPlayer::onPlaylistItemSelected(int index)
{
    if (index >= 0 && index < collectedSongs.size()) {
        playSong(collectedSongs[index]);
    }
}

// 播放列表项移除
void MusicPlayer::onPlaylistRemoveSong(const QString &songId)
{
    for (int i = 0; i < collectedSongs.size(); ++i) {
        if (collectedSongs[i].id == songId) {
            collectedSongs.removeAt(i);
            break;
        }
    }
    if (currentSong.id == songId) {
        player->stop();
        titleLabel->setText("暂无歌曲");
        singerLabel->setText("");
        playBtn->setIcon(QIcon(":/暂停"));
    }
    musicDao->removeFromCollection(songId);
    collectedSongs = musicDao->getAllCollectedMusic();
    playlistWindow->updateList(collectedSongs);
}

// 网络请求完成
void MusicPlayer::onNetworkRequestFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "请求失败:" << reply->errorString();
        reply->deleteLater();
        return;
    }
    
    QByteArray data = reply->readAll();
    reply->deleteLater();
    
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qDebug() << "JSON解析错误:" << parseError.errorString();
        return;
    }
    
    QString requestType = reply->property("requestType").toString();
    if (requestType == "lyric") {
        // 处理歌词响应
        QJsonObject root = jsonDoc.object();
        if (root["code"].toInt() == 200 && root.contains("lrc")) {
            QJsonObject lrc = root["lrc"].toObject();
            QString lyricText = lrc["lyric"].toString();
            parseLyrics(lyricText);
            
            // 启动歌词更新定时器
            lyricTimer->start(30); // 每100ms更新一次
        } else {
            qDebug() << "未获取到歌词";
            lyricListWidget->clear();
            lyricListWidget->addItem("暂无歌词");
        }
    } else {
        bool isSuccess;
        songs = MusicJsonParser::parseMusicJson(jsonDoc.object(), isSuccess);
        currentSearchResults.clear();
        
        for (auto &song : songs) {
            MusicInfo info;
            info.id = song.id();
            info.title = song.name();
            info.singer = song.artist();
            info.url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(info.id);
            currentSearchResults.append(info);
            
            QStandardItem *item = new QStandardItem(info.title + " - " + info.singer);
            item->setData(info.id, SongIdRole);
            item->setData(info.title, songTitleRole);
            item->setData(info.singer, songSingerRole);
            item->setData(info.url, SongUrlRole);
            model->appendRow(item);
        }
        
        int rowHeight = resultView->sizeHintForRow(0);
        int visibleRows = qMin(5, songs.size());
        resultPopup->setFixedHeight(rowHeight * visibleRows + 5);
        resultView->setFixedHeight(rowHeight * visibleRows + 5);
        positionResultPopup();
        resultPopup->show();
    }
}

// 搜索结果点击
void MusicPlayer::onResultViewClicked(const QModelIndex &index)
{
    searchEdit->setText(index.data().toString());
    resultPopup->hide();
    
    QString id = index.data(SongIdRole).toString();
    QString title = index.data(songTitleRole).toString();
    QString singer = index.data(songSingerRole).toString();
    QString url = index.data(SongUrlRole).toString();
    
    currentSong.id = id;
    currentSong.title = title;
    currentSong.singer = singer;
    currentSong.url = url;
    currentSong.isCollected = musicDao->isMusicCollected(id);
    
    playSong(currentSong);
}

// 定位结果弹窗
void MusicPlayer::positionResultPopup()
{
    if (!searchEdit || !resultPopup) return;
    
    QPoint globalPos = searchEdit->mapToGlobal(QPoint(0, searchEdit->height()));
    QRect screen = QApplication::desktop()->availableGeometry(this);
    if (globalPos.y() + resultPopup->height() > screen.bottom()) {
        globalPos = searchEdit->mapToGlobal(QPoint(0, -resultPopup->height()));
    }
    
    resultPopup->move(globalPos);
    resultPopup->setFixedWidth(searchEdit->width());
}

// 歌词解析函数
void MusicPlayer::parseLyrics(const QString &lyricText)
{
    lyricMap.clear();
    lyricTimes.clear();
    lyricListWidget->clear();
    
    // 解析LRC格式歌词
    QRegularExpression rx("\\[(\\d+):(\\d+)\\.(\\d+)\\](.*)");
    QStringList lines = lyricText.split("\n");
    
    for (const QString &line : lines) {
        QRegularExpressionMatch match = rx.match(line);
        if (match.hasMatch()) {
            int minutes = match.captured(1).toInt();
            int seconds = match.captured(2).toInt();
            int milliseconds = match.captured(3).toInt() * 10; // 百分之一秒转为毫秒
            
            qint64 timeMs = (minutes * 60 + seconds) * 1000 + milliseconds;
            QString lyric = match.captured(4).trimmed();
            
            if (!lyric.isEmpty()) {
                lyricMap[timeMs] = lyric;
                lyricTimes.append(timeMs);
                
                // 添加到歌词列表
                QListWidgetItem *item = new QListWidgetItem(lyric);
                item->setTextAlignment(Qt::AlignCenter);
                lyricListWidget->addItem(item);
            }
        }
    }
    
    // 对时间点排序
    std::sort(lyricTimes.begin(), lyricTimes.end());
    currentLyricIndex = -1;
}

// 获取歌词
void MusicPlayer::fetchLyrics(const QString &songId)
{
    QString url = QString("http://music.163.com/api/song/lyric?id=%1&lv=1&kv=1&tv=-1").arg(songId);
    QNetworkRequest request(url);
    QNetworkReply *reply = netManager->get(request);
    reply->setProperty("requestType", "lyric");
}

